extends Enemy

enum State{
	IDLE,
	WALK,
	RUN,
	REST,
}


func _ready():
	# 给敌人设置目标
	target = get_tree().get_first_node_in_group("player")
	pass

func tick_physics(state : State,delta : float) ->void:
	match state:
		State.IDLE:
			run_after(0.0,delta)
		State.WALK:
			freedom(speed,delta)
		State.RUN:
			run_after(speed,delta)
		State.REST:
			run_after(0.0,delta)


func get_next_state(state : State) ->State:
	var distance = (target.global_position-self.global_position).length()
	if distance<100 and distance>20:
		return State.RUN
	
	match state:
		State.IDLE:
			# await get_tree().create_timer(1.0).timeout
			if state_machine.state_time>1:
				return State.WALK
			
		State.WALK:
			if state_machine.state_time>3:
				return State.IDLE
			
		State.RUN:
			if distance<=20:
				return State.REST
			if distance>=100:
				return State.WALK
		State.REST:
			if state_machine.state_time>5:
				return State.IDLE
	return state


func transitiona_state(from : State,to : State)->void:
	
	match to :
		State.IDLE:
			print("->IDLE")
			pass
		State.WALK:
			print("->WALK")
			pass
		State.RUN:
			print("->RUN")
			pass
		State.REST:
			print("->REST")
			pass

func run_after(speed : float, delta : float):
	var run_direction = (target.global_position-self.global_position).normalized()
	# sprite.flip_h = run_direction.x<0
	velocity = run_direction * speed * delta
	move_and_slide()


func freedom(speed : float, delta : float):
	# sprite.flip_h = rand_direction.x<0
	velocity = rand_direction * speed * delta
	move_and_slide()
